from sqlalchemy.orm import Session
from models.models import LearnMaterial
from schemas.material import MaterialCreate, MaterialContent
from PyPDF2 import PdfReader
from pathlib import Path

def create_material(db: Session, material: MaterialCreate):
    db_material = LearnMaterial(title=material.title, file_path=material.file_path, user_id=material.user_id)
    db.add(db_material)
    db.commit()
    db.refresh(db_material)
    return db_material

def get_material(db: Session, material_id: int, user_id: int):
    return db.query(LearnMaterial).filter(LearnMaterial.id == material_id, LearnMaterial.user_id == user_id).first()

def get_all_materials(db: Session, user_id: int):
    return db.query(LearnMaterial).filter(LearnMaterial.user_id == user_id).all()

def update_material(db: Session, material_id: int, title: str, file_path: str, user_id: int):
    material = db.query(LearnMaterial).filter(LearnMaterial.id == material_id, LearnMaterial.user_id == user_id).first()
    if material:
        material.title = title
        material.file_path = file_path
        db.commit()
        db.refresh(material)
        return material
    return None

def delete_material(db: Session, material_id: int, user_id: int):
    material = db.query(LearnMaterial).filter(LearnMaterial.id == material_id, LearnMaterial.user_id == user_id).first()
    if material:
        db.delete(material)
        db.commit()
        return True
    return False

def get_material_content(db: Session, content_list: list[MaterialContent]):
    from collections import defaultdict

    # Step 1: Group content by material_id
    material_pages = defaultdict(list)
    for content in content_list:
        material_pages[content.material_id].append(content.page_number)

    # Step 2: Fetch file_path and read specified PDF pages
    combined_content = ""
    for material_id, pages in material_pages.items():
        material = db.query(LearnMaterial).filter(LearnMaterial.id == material_id).first()
        if material:
            file_path = material.file_path
            try:
                # 获取main.py所在的根目录路径
                ROOT_DIR = Path(__file__).parent.parent
                # 文件上传目录相对于根目录的路径
                UPLOAD_DIR = ROOT_DIR / "static" 
                # Step 3: Read only specified PDF pages
                reader = PdfReader(UPLOAD_DIR / file_path)
                for page_number in pages:
                    page_number = page_number - 1 # 和前端pdf的页码不一样
                    if 0 <= page_number < len(reader.pages):  # Ensure page_number is within range
                        page = reader.pages[page_number]
                        combined_content += page.extract_text() + "\n"
            except Exception as e:
                raise Exception(f"Error reading PDF for material_id {material_id}: {e}")

    # Step 4: Return combined content
    return combined_content
